import request from '@/utils/request';
import store from '@/store';

export function randomString(len) {
  len = len || 32;
  var chars = 'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678';
  var maxPos = chars.length;
  var pwd = '';
  for (var i = 0; i < len; i++) {
    pwd += chars.charAt(Math.floor(Math.random() * maxPos));
  }
  return pwd;
}

export function getSuffix(filename) {
  let pos = filename.lastIndexOf('.')
  let suffix = ''
  if (pos !== -1) suffix = filename.substring(pos)
  console.log('fffffffffffffffff', filename, suffix)
  return suffix
}

export function aliyunOssApi(dir) {
  return request({
    url: '/journal/admin/common/upload?dir=' + dir,
    method: 'get'
  })
}
/**
 * 获取阿里云OSS凭证
 * @param {*} dir
 */
export async function aliyunOss(dir) {
  console.log('>><<', dir)
  let ossPolicy = store.state.common.ossPolicy;
  if (ossPolicy === null) {
    await aliyunOssApi(dir).then(response => {
      ossPolicy = response.data;
    });
    store.commit('ossPolicy', ossPolicy);
  }
  return {
    OSSAccessKeyId: ossPolicy.accessid,
    policy: ossPolicy.policy,
    Signature: ossPolicy.signature,
    expire: ossPolicy.expire,
    key: `${ossPolicy.dir}/${randomString(36)}`
  };
}

/**
 * ajax上传阿里云OSS
 * @param {*} fileObj
 * @param {*} dir - 目录
 * @param {*} fileName - 文件名 - 默认文件名称
 */
export async function uploadFile(fileObj, dir, fileName) {
  let ossPolicy = store.state.common.ossPolicy;
  if (
    ossPolicy === null ||
    ossPolicy.dir !== dir ||
    ossPolicy.expire > new Date().getTime() / 1000 + 120
  ) {
    await aliyunOssApi(dir).then(response => {
      ossPolicy = response.data;
    });
    store.commit('ossPolicy', ossPolicy);
  }
  const formData = new FormData();
  let key = `${ossPolicy.dir}${Math.random()
    .toString(36)
    .substring(2)}${Math.random()
    .toString(36)
    .substring(2)}`;
  formData.append('OSSAccessKeyId', ossPolicy.accessid);
  formData.append('policy', ossPolicy.policy);
  formData.append('Signature', ossPolicy.signature);
  formData.append('expire', ossPolicy.expire);
  formData.append('key', key);
  formData.append('file', fileObj.file);

  request({
    url: ossHost,
    method: 'post',
    data: formData
  }).then(res => {
    console.log('oli', res)
    if (res.status === 204) {
      return key;
    }
  });
  return null;
}

/**
 * 阿里云OSS域名
 */
export const ossHost = 'https://r-space.oss-cn-shanghai.aliyuncs.com/';
